﻿using AiMoWindows.CodeScripts;
using Microsoft.CodeAnalysis.Text;

namespace AiMoWindows.MainActions.ScriptActions.SubActions
{
    class ExecuteCodeAction(ActionsController actions, ScriptManager scriptManager)
    {
        readonly ActionsController actions = actions;
        readonly ScriptManager scriptManager = scriptManager;
        public async Task ExecuteCode()
        {
            actions.ClearDebugPrint();
            if (!await actions.SyncAction.SyncScriptsWithFormat())
            {
                // 无法同步，格式有误
                return;
            }
            SourceText sourceText = await actions.CurrentSourceText();
            if (scriptManager.CompileMode != Mode.ScriptComplileMode.ExternalAssemblies)
            {
                // 当编译为AiMo的时候，才进行代码校验
                if (!Compiler.Utils.PreCheck(sourceText.Lines.Select(x => x.ToString()), out string error))
                {
                    actions.Printer.PrintDebug(error);
                    return;
                }
            }

            if (scriptManager.Compile(out string compileErrors, out string compileTime))
            {
                actions.Printer.PrintDebug(compileTime);
                await Task.Run(() => { scriptManager.ExcutingCommand(actions.Printer); });
            }
            actions.Printer.PrintDebug(compileErrors);
        }
    }
}
